package main

import (
	"net"
	"strings"
)

type User struct {
	Name string
	Addr string
	C    chan string
	conn net.Conn

	server *Server
}

// 创建用户
func NewUser(conn net.Conn, server *Server) *User {
	userAddr := conn.RemoteAddr().String()
	user := &User{
		Name:   userAddr,
		Addr:   userAddr,
		C:      make(chan string),
		conn:   conn,
		server: server,
	}
	//启动该用户的监听
	go user.ListenMessage()
	return user
}
func (this *User) Online() { //用户上线
	//用户上线，将用户添加到OnlineMap中，广播消息
	this.server.maplock.Lock()
	this.server.OnlineMap[this.Name] = this
	this.server.maplock.Unlock()
	//广播用户上线消息
	this.server.BroadCast(this, "User Online")
}

func (this *User) Offline() { //用户下线
	//用户下线，将用户添加到OnlineMap中，广播消息
	this.server.maplock.Lock()
	delete(this.server.OnlineMap, this.Name)
	this.server.maplock.Unlock()
	//广播用户下线消息
	this.server.BroadCast(this, "User Offline")
}
func (this *User) SendMsg(msg string) { //给当前用户发送消息
	this.conn.Write([]byte(msg))
}

func (this *User) DoMessage(msg string) { //用户处理消息
	if msg == "who" {
		//查询在线用户
		this.server.maplock.Lock()
		for _, user := range this.server.OnlineMap {
			onlineMsg := "[" + user.Addr + "]" + user.Name + ":" + "online....\n"
			this.SendMsg(onlineMsg)
		}
		this.server.maplock.Unlock()
	} else if len(msg) > 7 && msg[:7] == "rename|" {
		// rename | NEWNAME
		newName := strings.Split(msg, "|")[1]
		// 判断name是否存在
		if _, ok := this.server.OnlineMap[newName]; ok {
			this.SendMsg("This Name Have Been Used,Please Try Another Name\n")

		} else {
			this.server.maplock.Lock()
			delete(this.server.OnlineMap, this.Name)
			this.server.OnlineMap[newName] = this
			this.server.maplock.Unlock()
			this.Name = newName
			this.SendMsg("Have Updated Your New Name:" + newName + "\n")
		}

	} else if len(msg) > 4 && msg[:3] == "to|" { //私聊发送消息
		// to | somebody | msg
		// 1.获取somebody的名称
		MSG := strings.Split(msg, "|")
		toName := MSG[1]
		if toName == "" {
			this.SendMsg("usage: to|toName|Msg\n")
			return
		}
		// 2.获取msg
		toMsg := MSG[2]
		if toMsg == "" {
			this.SendMsg("usage: to|toName|Msg\nNo Msg\n")
			return
		}
		//检测name是否存在
		if _, ok := this.server.OnlineMap[toName]; !ok {
			this.SendMsg("User:" + toName + "Doesn't exsist\n")
		} else {
			toUser := this.server.OnlineMap[toName]
			toUser.SendMsg("[" + this.Name + "]:" + toMsg)
		}

	} else {
		this.server.BroadCast(this, msg)
	}

	//修改自己的名称

}

// 监听channel的方法,channel有消息则发给客户端
func (this *User) ListenMessage() {
	for {
		msg := <-this.C
		this.conn.Write([]byte(msg + "\n"))
	}
}
